package com.queming.service.music;

import com.queming.music.dto.MusicDto;
import com.queming.music.dto.MusicSearchFilter;
import com.queming.music.entity.Music;
import com.queming.music.enums.MusicStatus;
import com.queming.core.exception.ExceptionType;
import com.queming.core.mapper.MapperInterface;
import com.queming.music.mapper.MusicMapper;
import com.queming.music.repository.MusicRepository;
import com.queming.music.repository.specs.MusicSpecification;
import com.queming.core.respository.specs.SearchCriteria;
import com.queming.core.respository.specs.SearchOperation;
import com.queming.service.General.GeneralServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

/**
 * @author chencidiao
 * @date 2022/05/03 15:49
 **/
@Service
public class MusicServiceImpl extends GeneralServiceImpl<Music,MusicDto> implements MusicService{

    MusicRepository musicRepository;
    @Autowired
    public void setMusicRepository(MusicRepository musicRepository) {
        this.musicRepository = musicRepository;
    }
    MusicMapper musicMapper;
    @Autowired
    public void setMusicMapper(MusicMapper musicMapper) {
        this.musicMapper = musicMapper;
    }


    @Override
    public void publish(String id) {
        Music music = getEntity(id);
        music.setStatus(MusicStatus.PUBLISHED);
        musicRepository.save(music);
    }

    @Override
    public void close(String id) {
        Music music = getEntity(id);
        music.setStatus(MusicStatus.CLOSED);
        musicRepository.save(music);
    }

    @Override
    public Page<MusicDto> search(MusicSearchFilter musicSearchFilter) {
        if (musicSearchFilter==null){
            musicSearchFilter=new MusicSearchFilter();
        }
        MusicSpecification specs = new MusicSpecification();
        specs.add(new SearchCriteria("name",musicSearchFilter.getName(), SearchOperation.MATCH));
        Sort sort = Sort.by(Sort.Direction.DESC, "createdTime");
        Pageable pageable=PageRequest.of(musicSearchFilter.getPage()-1,musicSearchFilter.getSize(),sort);

        Page<Music> all = musicRepository.findAll(specs, pageable);

        return all.map(musicMapper::toDto);
    }

    @Override
    public JpaRepository<Music, String> getRepository() {
        return musicRepository;
    }

    @Override
    public MapperInterface<Music, MusicDto> getMapper() {
        return musicMapper;
    }

    @Override
    public ExceptionType getNotFoundExceptionType() {
        return ExceptionType.MUSIC_NOT_FOUND;
    }
}
